<?php

namespace app\Api\controller;

use app\common\business\SCategory;
use app\common\business\SGoods as SGoodsBus;
use app\common\lib\Check;
use app\common\model\mysql\SGoodsImage;
use app\common\model\mysql\SGoodsVisitors;

class Goods extends ApiBase
{
    /**
     * 构建查询条件数组
     *
     * @param string $goodsName 商品名称
     * @param int $typeId 类型ID
     * @param int $categoryId 分类ID
     * @return array 查询条件数组
     */
    private function buildWhereConditions($goodsName, $typeId, $categoryId, &$noMatchingGoods)
    {
        $where = [];
        // 添加商品名称查询条件
        if ($goodsName) {
            $where[] = ['goods_name', 'like', '%' . $goodsName . '%'];
        }
        // 添加类型查询条件
        if ($typeId) {
            switch ($typeId) {
                case 1:
                    $where[] = ['is_hot', '=', 1];
                    break;
                case 2:
                    $where[] = ['is_benefit', '=', 1];
                    break;
                case 3:
                    $where[] = ['is_best', '=', 1];
                    break;
                case 4:
                    $where[] = ['is_new', '=', 1];
                    break;
                case 5:
                    $where[] = ['is_good', '=', 1];
                    break;
            }
        }

        // 添加分类查询条件
        if ($categoryId) {
            $categoryData = (new SCategory())->getCategoryById($categoryId);
            if ($categoryData) {
                $categoryIdArray = $this->getCategoryIdsByParentId($categoryData);
                // 获取符合条件的商品ID
                $map[] = ['category_id', 'in', $categoryIdArray];
                $goodsId = (new SGoodsBus())->getNormalGoodsFieldData($map, 'goods_id');
                if ($goodsId) {
                    $where[] = ['goods_id', 'in', $goodsId];
                } else {
                    $noMatchingGoods = true;
                }
            }else{
                $noMatchingGoods = true;
            }
        }

        // 添加通用查询条件
        $where[] = ['status', '=', '0'];
        $where[] = ['goods_type', '=', 0];
        $where[] = ['del_flag', '=', '0'];

        return $where;
    }

    /**
     * 根据父分类ID获取所有子分类ID（包括自身）
     *
     * @param array $categoryData 分类数据
     * @return array 分类ID数组
     */
    private function getCategoryIdsByParentId(array $categoryData)
    {
        if ($categoryData['parent_id'] === 0) {
            // 根分类，获取所有子分类ID
            $cateWhere[] = ['parent_id', '=', $categoryData['category_id']];
            $subCategories = (new SCategory())->getCategoryIdsArr($cateWhere, 'category_id');
            $categoryIdArray = array_merge([$categoryData['category_id']], $subCategories);
        } else {
            // 非根分类，只获取自身ID
            $categoryIdArray = [$categoryData['category_id']];
        }
        return $categoryIdArray;
    }

    // 商品列表
    public function goodsList()
    {
        // 获取分页参数
        $noMatchingGoods = false; // 初始化标志位
        $page = $this->request->param('pageNum', 1);
        $limit = $this->request->param('pageSize', 10);

        // 获取查询条件
        $goodsName = $this->request->param('goods_name', "");
        $typeId = $this->request->param('type_id', "");
        $categoryId = $this->request->param('category_id', "");

        // 构建查询条件数组
        $where = $this->buildWhereConditions($goodsName, $typeId, $categoryId, $noMatchingGoods);
        // 执行数据库查询
        try {
            if ($noMatchingGoods) {
                // 如果没有符合条件的商品，返回空结果
                return show(config("status.success"), "商品数据列表", []);
            }
            $goodsField = "goods_id, goods_name, selling_price, price, stock, quantity_sold, main_img_url";
            $configData = (new SGoodsBus())->getNormalGoodsData($where, $goodsField, $limit, $page);
            foreach ($configData['data'] as &$goods){
                $goods['main_img_url'] = (new Check())->checkUrl($goods['main_img_url']);
            }
            return show(config("status.success"), "商品数据列表", $configData);
        } catch (\Exception $e) {
            return show(config("status.error"), $e->getMessage(), []);
        }
    }

    // 商品详情
    public function goodsDetails(){
        $goodsId = $this->request->param("goodsId","","trim");
        if(empty($goodsId)){
            return show(config("status.error"),"参数不能为空");
        }
        try {
            $goodsField = "goods_id,goods_sn,goods_name,goods_unit,selling_price,price,stock,desc,goods_details,quantity_sold,main_img_url,is_extension,extension_one,extension_two,sales,goods_views,number_visitors";
            $goodsData = (new SGoodsBus())->getGoodsById($goodsId,$goodsField);
            $goodsData['main_img_url'] = (new Check())->checkUrl($goodsData['main_img_url']);
            $getImagesArr = (new SGoodsImage())->getImages($goodsId);
            $goodsData['goodsImg'] = $getImagesArr;
            foreach ($goodsData['goodsImg'] as &$goods){
                $goods = (new Check())->checkUrl($goods);
            }
            $goodsData['quantity_sold'] = $goodsData['quantity_sold']+$goodsData['sales'];
            unset($goodsData['sales']);
            //查找数据库是否存在此条记录
            $passGoodsVisitorsData = (new SGoodsVisitors())->getGoodsVisitorsData($goodsId,request()->ip());
            if(empty($passGoodsVisitorsData)){
                $data['visitors_ip'] = request()->ip();
                $data['goods_id'] = $goodsId;
                (new SGoodsVisitors())->addGoodsVisitors($data);
                //增加商品访客量
                $goodsUpdate['number_visitors'] = $goodsData['number_visitors']+1;
            }
            //增加商品浏览量
            $goodsUpdate['goods_views'] = $goodsData['goods_views']+1;
            (new SGoodsBus())->updateById($goodsId,$goodsUpdate);
        }catch (\Exception $e){
            $goodsData = [];
        }
        return show(config("status.success"),"商品详情",$goodsData);
    }
}
